from django.contrib.contenttypes.models import ContentType
from django.db import transaction
from django.shortcuts import render
from rest_framework.views import APIView

from utils.customer_modelviewset import CustomerViewSet
from utils.exception import CustomError
from utils.permission import IsMemberUser
from utils import response_error, response_ok
from .models import Comment
from .serializers import CommentSerializers
from ..models import MemberRecord


class CommentlikeViewSet(APIView):
    '''点赞'''
    permission_classes = (IsMemberUser,)

    def post(self, request, id):
        comment = Comment.objects.filter(pk=id).first()
        if not comment:
            return response_error('为找到对应的评论')

        with transaction.atomic():

            member_record = MemberRecord.objects.filter(content_type=Comment.get_content_type(), object_id=id,
                                                        member=self.request.user, operate=MemberRecord.LIKE).first()
            if member_record:
                # 存在，删除
                comment.like_count -= 1
                comment.save()
                member_record.delete()
                return response_ok()
            # 不存在，创建
            comment.like_count += 1
            comment.save()
            MemberRecord.objects.create(content_object=comment, member=self.request.user, operate=MemberRecord.LIKE,
                                        describe='点赞')
        return response_ok()


class CommentViewSet(CustomerViewSet):
    permission_classes = (IsMemberUser,)
    queryset = Comment.objects.filter(delete=False)
    serializer_class = CommentSerializers

    def create(self, request, *args, **kwargs):
        try:
            content = request.POST.get('content', None)
            content_type_model = request.POST.get('content_type', None)
            object_id = request.POST.get('object_id', None)

            if not content or not content_type_model or not object_id:
                return response_error('缺少参数')

            # 回复
            parent_id = request.POST.get('parent_id', None)
            parent = None
            if parent_id:
                parent = Comment.objects.filter(id=parent_id).first()

            content_type = ContentType.objects.get(model=content_type_model.lower())
            if not content_type:
                return response_error('未找到(%s)对应实体' % content_type)
            # ContentType表对象有model_class() 方法，取到对应model
            EntityModel = content_type.model_class()
            instance = EntityModel.objects.filter(id=object_id).first()
            if not instance:
                return response_error('未找到实体(%s)对应的（id=%s）实例' % (EntityModel.__name__, object_id))

            with transaction.atomic():
                comment = Comment.objects.create(content_type=content_type, object_id=object_id,
                                                 member=self.request.user,
                                                 content=content, parent=parent)

                MemberRecord.objects.create(content_type=comment.get_content_type(), member=self.request.user,
                                            object_id=comment.id, operate=MemberRecord.COMMENT, describe='发表了评论')

        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            import traceback
            traceback.print_exc()
            return response_error(str(e))

        return response_ok()

    def destroy(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                instance = self.get_object()
                if instance.member == self.request.user:
                    print('可以删除')
                    print(instance.member)
                print('不可以删除')
                print(instance.member)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok()
